﻿using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Transactions;
using Newtonsoft.Json; 
using T.FAS.Runtime.Base.Entity;
using T.ServiceComponent.DAC.Service;
using System.Reflection;

namespace T.FAS.Runtime.Base.Dao
{
    public class CodeItemELBDao : DaoService<CodeItem>
    {
        public const string MetaDataID = "CodeItem";
        public const string MetaDataName = "数据库";
         
        public override string TableName => "FAS_CodeItems";
        public override string IDColumnName => "NM";

        private string ForeignKeyName { get; } = nameof(CodeItem.SetId);

        public override List<string> ExceptColumnName => new List<string>
        { 
        };        
         
        public CodeItemELBDao() : base()
        {
            DBName = "TFAS";
        }

        public List<CodeItem> GetCodeItems(Dictionary<string, string> filter)
        {
            var result = new List<CodeItem>();
            if (filter == null)
            {
                return result;
            }
            string where = string.Empty;
            if (filter.ContainsKey("SetId"))
                where = $"SetId='{filter["SetId"]}'";
            List<object> objects = base.GetObjectsByFilter(where);
            if (objects != null)
            {
                objects.ForEach(obj => result.Add(obj as CodeItem));
            }
            return result;
        }

        public CodeItem GetCodeItemByID(string NM)
        {
            return this.GetObject(NM);
        }

        public CodeItem GetCodeItemBySetId(string setId)
        {
            List<object> objects = base.GetObjectsByFilter($"{ForeignKeyName}='{setId}'");
            return objects?.FirstOrDefault() as CodeItem;
        }

        public void SaveCodeItem(CodeItem codeItem)
        {
            this.Add(new List<object> { codeItem });
        }

        public void SaveCodeItems(List<CodeItem> codeItems)
        {
            this.Add(codeItems);
        }

        public void DeleteCodeItem(string NM)
        {
            this.Delete(new List<string> { NM });
        }

        public void DeleteCodeItemsBySetId(string SetId)
        {
            this.DB.ExecSqlStatement($"DELETE FROM {TableName} WHERE SETID='{SetId}'");
        }

        public int CheckCodeItemUnique(Dictionary<string, string> filter)
        {
            return (int)(long)this.DB.ExecuteScalar($@"select count(1) from fas_codeitems
            where SetId ='{filter["SetId"]}'
			and Code ='{filter["Code"]}'");
        }
    }
}
